<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="updateNettyConfig"
      @refresh="refresh"
      :fastConfig="fastConfig"
    />
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef } from 'vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { getNettyConfig, updateNettyConfig } from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'Netty',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 7 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  field: string,
  layout?: any,
  required: boolean = false,
  props?: any,
): ItemProps => {
  return {
    label,
    type: 'input',
    field,
    props: { placeholder: `请输入${label}`, allowClear: false, ...props },
    rules: [{ required, message: `请输入${label}`, trigger: 'blur' }],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const radioOptions = [
  { value: '0', label: '关闭' },
  { value: '1', label: '开启' },
];
const desktopTerminal = props.pageData.deviceType == '3';
const isNewVersion = Number(props.pageData.protobufVersion) > 0;

const items = computed<ProFormProps['items']>(() => [
  itemRender('服务配置'),
  itemObj('服务地址', 'nettyAddress'),
  itemObj('服务端口', 'nettyPort', undefined, true),
  itemObj('重连时间', 'nettyReconnectTime', undefined, true),
  itemObj('心跳时间', 'nettyBeatDelayTime', undefined, true),
  ...(isNewVersion && !desktopTerminal
    ? [
        itemRender('备用服务配置'),
        {
          label: '开启备用服务',
          type: 'radio',
          field: 'isOpenAlternateNetty',
          props: { options: radioOptions },
          rules: [
            {
              required: true,
              message: '请选择是否开启备用服务',
              trigger: 'blur',
            },
          ],
        } as ItemProps,
        itemObj(
          '备用服务地址',
          'alternateNettyAddress',
          undefined,
          formState.value.isOpenAlternateNetty == '1' ? true : false,
        ),
        itemObj(
          '备用服务端口',
          'alternateNettyPort',
          undefined,
          formState.value.isOpenAlternateNetty == '1' ? true : false,
        ),
      ]
    : []),
]);

props.pageData.nettyConfigsJson
  ? (() => {
      formState.value = JSON.parse(props.pageData.nettyConfigsJson);
      loaded.value = true;
    })()
  : getNettyConfig(props.pageData.code).then((res: any) => {
      formState.value = res.data;
      formState.value.code = props.pageData.code;
      loaded.value = true;
    });

defineExpose({
  async save() {
    const data = await formRef.value.validate();
    props.pageData.nettyConfigsJson = JSON.stringify(data);
  },
});
</script>
